// pages/main/organization/organization.js
Page({
  data: {
    currentTab: 'organization', // 默认选中组织架构
    searchKeyword: '',
    loading: false,
    userInfo: {},
    expandedDeptId: null, // 当前展开的部门ID
    expandedDeptIds: [], // Lin UI Collapse 组件需要的展开项ID数组
    departments: [
      { id: 16, name: '总裁办', count: 3, members: [
        { id: 101, zh_name: '张总裁', role: '总裁', wx_avatar_url: '' },
        { id: 102, zh_name: '李副总裁', role: '副总裁', wx_avatar_url: '' },
        { id: 103, zh_name: '王秘书', role: '秘书', wx_avatar_url: '' }
      ]},
      { id: 2, name: '信息技术部', count: 5, members: [
        { id: 201, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 202, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 203, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 204, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' },
        { id: 205, zh_name: '钱技术员', role: '技术员', wx_avatar_url: '' }
      ]},
      { id: 3, name: '商务服务部', count: 8, members: [
        { id: 301, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 302, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 303, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 304, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 4, name: '计划财务部', count: 4, members: [
        { id: 401, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 402, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 403, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 404, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 5, name: '行政人事部', count: 6, members: [
        { id: 501, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 502, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 503, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 504, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' },
        { id: 505, zh_name: '钱技术员', role: '技术员', wx_avatar_url: '' },
        { id: 506, zh_name: '孙专员', role: '专员', wx_avatar_url: '' }
      ]},
      { id: 6, name: '分公司管理部', count: 3, members: [
        { id: 601, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 602, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 603, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' }
      ]},
      { id: 7, name: '规划设计中心', count: 12, members: [
        { id: 701, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 702, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 703, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 704, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 8, name: '数据勘测中心', count: 10, members: [
        { id: 801, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 802, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 803, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 804, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 9, name: '资源评价中心', count: 8, members: [
        { id: 901, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 902, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 903, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 904, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 10, name: '评估咨询一中心', count: 15, members: [
        { id: 1001, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 1002, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 1003, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 1004, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 11, name: '评估咨询二中心', count: 12, members: [
        { id: 1101, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 1102, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 1103, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 1104, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 12, name: '经纪代理中心', count: 9, members: [
        { id: 1201, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 1202, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 1203, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 1204, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 13, name: '江阴事业中心', count: 7, members: [
        { id: 1301, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 1302, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 1303, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 1304, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 14, name: '南京事业中心', count: 6, members: [
        { id: 1401, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 1402, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 1403, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 1404, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ]},
      { id: 15, name: '其它', count: 2, members: [
        { id: 1501, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 1502, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' }
      ]}
    ],
    sameDepartmentUsers: [],
    subordinates: []
  },

  onLoad: function() {
    this.loadUserInfo();
    // 根据当前标签加载数据
    if (this.data.currentTab === 'organization') {
      // 组织架构数据已在data中定义
    } else if (this.data.currentTab === 'department') {
      this.loadSameDepartmentUsers();
    } else if (this.data.currentTab === 'subordinate') {
      this.loadSubordinates();
    }
  },

  onShow() {
    this.loadUserInfo();
    
    // 根据当前标签加载数据
    if (this.data.currentTab === 'organization') {
      // 组织架构数据已在data中定义
    } else if (this.data.currentTab === 'department') {
      this.loadSameDepartmentUsers();
    } else if (this.data.currentTab === 'subordinate') {
      this.loadSubordinates();
    }
  },

  // 加载用户信息
  loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('user_info');
      if (userInfo) {
        this.setData({
          userInfo: userInfo
        });
      }
    } catch (e) {
      console.error('获取用户信息失败:', e);
    }
  },

  // 标签切换
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      currentTab: tab
    });

    // 根据标签加载对应数据
    if (tab === 'organization') {
      // 组织架构数据已经在data中定义
    } else if (tab === 'department') {
      // 同部门
      this.loadSameDepartmentUsers();
    } else if (tab === 'subordinate') {
      // 下属
      this.loadSubordinates();
    }
  },

  // 搜索输入变化（Lin UI 的 linchange 事件）
  onSearchChange(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    // 实时搜索
    this.filterUsers(keyword);
  },
  onShareAppMessage() {
  },
  // 搜索确认（Lin UI 的 linconfirm 事件）
  onSearchConfirm(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    this.filterUsers(keyword);
    console.log('搜索确认:', keyword);
  },

  // 清除搜索（Lin UI 的 linclear 事件）
  onSearchClear() {
    this.setData({ searchKeyword: '' });
    // 恢复原始数据
    this.loadCurrentTabData();
    console.log('清除搜索');
  },

  // 取消搜索（Lin UI 的 lincancel 事件）
  onSearchCancel() {
    this.setData({ searchKeyword: '' });
    // 恢复原始数据
    this.loadCurrentTabData();
    console.log('取消搜索');
  },

  // 筛选用户
  filterUsers(keyword) {
    if (!keyword) {
      this.loadCurrentTabData();
      return;
    }

    const lowerKeyword = keyword.toLowerCase();
    const currentTab = this.data.currentTab;

    if (currentTab === 'organization') {
      // 在组织架构中搜索
      const filteredDepts = this.data.departments.map(dept => {
        const filteredMembers = (dept.members || []).filter(member => {
          const name = (member.zh_name || '').toLowerCase();
          const role = (member.role || '').toLowerCase();
          return name.includes(lowerKeyword) || role.includes(lowerKeyword);
        });
        return { ...dept, members: filteredMembers };
      }).filter(dept => 
        dept.name.toLowerCase().includes(lowerKeyword) || 
        (dept.members && dept.members.length > 0)
      );
      this.setData({ departments: filteredDepts });
    } else if (currentTab === 'department') {
      // 在同部门中搜索
      const filtered = this.data.sameDepartmentUsers.filter(user => {
        const name = (user.zh_name || '').toLowerCase();
        const role = (user.role || '').toLowerCase();
        return name.includes(lowerKeyword) || role.includes(lowerKeyword);
      });
      this.setData({ sameDepartmentUsers: filtered });
    } else if (currentTab === 'subordinate') {
      // 在下属中搜索
      const filtered = this.data.subordinates.filter(user => {
        const name = (user.zh_name || '').toLowerCase();
        const role = (user.role || '').toLowerCase();
        return name.includes(lowerKeyword) || role.includes(lowerKeyword);
      });
      this.setData({ subordinates: filtered });
    }
  },

  // 加载当前标签的数据
  loadCurrentTabData() {
    const tab = this.data.currentTab;
    if (tab === 'organization') {
      // 重新加载组织架构数据（这里可以从原始数据恢复）
      this.onLoad();
    } else if (tab === 'department') {
      this.loadSameDepartmentUsers();
    } else if (tab === 'subordinate') {
      this.loadSubordinates();
    }
  },

  // 部门点击 - 兼容原有方法
  onDepartmentTap(e) {
    const dept = e.currentTarget.dataset.dept;
    console.log(e.currentTarget.dataset.dept.name)
    const deptId = dept.id;
    // 如果点击的是当前已展开的部门，则收起
    if (this.data.expandedDeptId === deptId) {
      this.setData({
        expandedDeptId: null
      });
      return;
    }
    
    // 加载部门成员
    this.loadDepartmentMembers(deptId);
  },

  // Lin UI Collapse 展开事件
  onDepartmentExpand(e) {
    console.log('展开事件触发:', e);
    const deptId = e.detail;
    console.log('部门展开:', deptId);
    
    // 更新展开状态
    this.setData({
      expandedDeptId: deptId,
      expandedDeptIds: [deptId]
    });
    
    // 加载部门成员
    this.loadDepartmentMembers(deptId);
  },

  // Lin UI Collapse 折叠事件
  onDepartmentFold(e) {
    const deptId = e.detail;
    console.log('部门折叠:', deptId);
    
    // 更新折叠状态
    this.setData({
      expandedDeptId: null,
      expandedDeptIds: []
    });
  },
  
  // 加载部门成员
  loadDepartmentMembers(deptId) {
    console.log('加载部门id为：'+deptId+' 的成员')
    // 设置加载状态
    this.setData({
      loading: true
    });
    
    // 模拟API请求延迟
    setTimeout(() => {
      // 生成模拟数据
      const mockMembers = [
        { id: 101, zh_name: '张经理', role: '部门经理', wx_avatar_url: '' },
        { id: 102, zh_name: '李工程师', role: '高级工程师', wx_avatar_url: '' },
        { id: 103, zh_name: '王助理', role: '行政助理', wx_avatar_url: '' },
        { id: 104, zh_name: '赵专员', role: '业务专员', wx_avatar_url: '' }
      ];
      
      console.log('生成的模拟数据:', mockMembers);
      
      // 更新部门成员数据
      const departments = this.data.departments.map(dept => {
        if (dept.id === deptId) {
          const updatedDept = { ...dept, members: mockMembers };
          console.log('更新部门数据:', updatedDept);
          return updatedDept;
        }
        return dept;
      });
      
      console.log('更新后的所有部门数据:', departments);
      
      // 更新状态
      this.setData({
        departments,
        expandedDeptId: deptId,
        loading: false
      });
      
      console.log('数据更新完成');
    }, 300); // 300ms延迟，让动画效果更自然
  },

  // 加载同部门用户
  loadSameDepartmentUsers() {
    const { userInfo } = this.data;
    if (!userInfo.part_id) return;

    // 这里应该调用API获取同部门用户
    // 暂时使用模拟数据
    const mockUsers = [
      { id: 1, zh_name: '张三', role: '部门经理', wx_avatar_url: '' },
      { id: 2, zh_name: '李四', role: '高级工程师', wx_avatar_url: '' },
      { id: 3, zh_name: '王五', role: '工程师', wx_avatar_url: '' }
    ];

    this.setData({
      sameDepartmentUsers: mockUsers
    });
  },

  // 加载下属用户
  loadSubordinates() {
    const { userInfo } = this.data;
    
    // 只有管理组或部门负责人才有下属
    if (!userInfo.Per_group || userInfo.Per_group.permit !== 1) {
      this.setData({ subordinates: [] });
      return;
    }

    // 这里应该调用API获取下属用户
    // 暂时使用模拟数据
    const mockSubordinates = [
      { id: 1, zh_name: '赵六', role: '项目经理', wx_avatar_url: '' },
      { id: 2, zh_name: '钱七', role: '业务员', wx_avatar_url: '' }
    ];

    this.setData({
      subordinates: mockSubordinates
    });
  }
});